import { useInViewport } from "ahooks";
import { useEffect, useState } from "react";
function useLazyData(target: any, apiFn: any) {
  const [result, setResult] = useState<any[]>([]);
  const [hasFetched, setHasFetched] = useState(false); // 新增状态控制是否已经请求过
  const [inViewport] = useInViewport(target.current, {
    threshold: 0.1,
  });
  useEffect(() => {
    if (inViewport && !hasFetched) {
      apiFn().then((res: any) => {
        setResult(res.result);
        setHasFetched(true); // 数据加载完成后标记为 true
      });
    }
  }, [hasFetched, inViewport]);

  return result;
}

export default useLazyData;
